package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService{

    @Autowired
    private MenuDao menuDao;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();//ThreadLocal
        PageHelper.startPage(currentPage,pageSize);
        Page<Menu> page=menuDao.findCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Menu> findAll() {

        return menuDao.findAll();
    }

    @Override
    public void add(Integer[] menuIds, Menu menu) {
        Integer parentMenuId=null;
        if (menuIds!=null && menuIds.length>0 && menuIds.length<2){
            parentMenuId=menuIds[0];
            menu.setParentMenuId(parentMenuId);
            menuDao.add(menu);
        }else {
            throw new RuntimeException();
        }
    }

    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    @Override
    public List<Integer> findMenuParentId(Integer id) {
        return menuDao.findMenuParentId(id);
    }

    @Override
    public void edit(Integer[] menuIds, Menu menu) {
        Integer parentMenuId=null;
        if (menuIds!=null && menuIds.length>0 && menuIds.length<2){
            parentMenuId=menuIds[0];
            menu.setParentMenuId(parentMenuId);
            menuDao.edit(menu);
        }else {
            throw new RuntimeException();
        }
    }

    @Override
    public void deleteMenu(Integer id) {
        Menu menu=menuDao.findByIdAndChildrens(id);
        if (menu==null){
            menuDao.delete(id);
        } else {
            throw new RuntimeException();
        }
    }


    //获取动态菜单
    @Override
    public List<Menu> getDynamicMenu(String name) {
        List<Menu>menulist = menuDao.findMenu(name);
        return menulist;
    }
    @Override
    public List<Integer> findMenuIdsByRoleId(Integer id) {
        return menuDao.findMenuIdsByRoleId(id);
    }
}
